import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { interceptStr } from '@/utils';

export default function useWatchRoute() {
  const route = useRoute();

  // 激活菜单按钮的
  const defaultActive = ref<string | any>('');
  const getDefaultActive = (): void => {
    if (route.meta.sidebar) {
      defaultActive.value = route.name;
    } else {
      defaultActive.value = interceptStr(route.name as string);
    }
  };

  // 面包屑
  const breadList = ref<Array<any>>([]);
  const getOtherBreadList = (): void => {
    const routeName = interceptStr(route.name as string);
    const twoMenu = route.matched[0].children.filter((item) => item.name === routeName);
    breadList.value = [route.matched[0], ...twoMenu, route.matched[route.matched.length - 1]];
  };
  const getMenuBreadList = (): void => {
    if (route.meta.sidebar) {
      breadList.value = route.matched;
      return;
    }
    getOtherBreadList();
  };

  watch(
    route,
    () => {
      getDefaultActive();
      getMenuBreadList();
    },
    {
      immediate: true,
    }
  );

  return { defaultActive, breadList };
}
